package com.unsafe5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//1、编写资源类
class Ticket {

    private int ticket = 100;

    public void sale() {
        if (ticket > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() +
                    "卖出一张票，票号：" + ticket);
            ticket--;
        } else {
            throw new RuntimeException("没有票了");
        }
    }

    public int getTicket() {
        return ticket;
    }

}

public class SaleTicketDemo05 {
    public static void main(String[] args) {
        new ReentrantLock();
//       2、创建资源类对象
        Ticket ticket = new Ticket();
//       3、启动对线程操作资源类对象
        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (;;){
                    ticket.sale();
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                while (true){
                    ticket.sale();
                }
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                while (true){
                    ticket.sale();
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }
}
// 结果：发现卖出进100张票
// 问题1：但有重复票或负数票的问题   原因：是因为线程安全的问题



